<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
// 下面的代码是固定写法
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKIDHQlwynOn02rSo03yCOTO6jFmGetzsZ4Q', // 身份识别ID
  SecretKey: 'IPURE1oTzIQMzVr34xkSzLZdVAfT8c1J' // 身份秘钥
})
export default {
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  watch: {
    value(newVal) {
      console.log(newVal, 555)
      this.imageUrl = newVal
    }
  },
  methods: {
    upload({ file }) {
      console.log(file)
      // 调用腾讯云sdk方法实现将图片上传到腾讯云
      cos.uploadFile(
        {
          Bucket: 'web87-1316386549' /* 存储桶 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: file.name /* 文件名 */,
          Body: file, // 上传文件对象
          SliceSize: 1024 * 1024 * 5,
          onProgress: function(progressData) {
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          this.showProgress = false
          if (err) {
            console.log('上传失败', err)
          } else {
            console.log('上传成功')
            console.log(data)
            this.imageUrl = `https://${data.Location}`
          }
        }
      )
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
